package com.kyc.kycxkplaygame.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import com.kyc.kycxkplaygame.util.ConstactUtil;
import com.kyc.kycxkplaygame.util.SharedPreferencesUtils;
import com.kyc.kycxkplaygame.util.TimeUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2018/6/13.
 */

public class TimeTiliService extends Service {

    public static final int TILI_ADD = 111;
    public static final int TILI_NOADD = 112;
    int tl = 0;
    public class TimeTiliBinder extends Binder {
        // 声明一个方法，getService。（提供给客户端调用）
        TimeTiliService getService() {
            // 返回当前对象LocalService,这样我们就可在客户端端调用Service的公共方法了
            return TimeTiliService.this;
        }
    }

    public Handler handler = new Handler(); /*{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TILI_ADD:
                    int obj = (int) msg.obj;
                    setTili(obj);
                    tl = 0;
                    handler.postDelayed(TiliRunnable, 1000);
                    break;
            }
        }
    };*/


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new TimeTiliBinder();
    }

    @Override
    public void onCreate() {
        handler.postDelayed(TiliRunnable, 5000);
    }

    Runnable TiliRunnable = new Runnable() {
        @Override
        public void run() {
            String oldtime = (String) SharedPreferencesUtils.getParam(TimeTiliService.this, "oldtime", "");
            if (!TextUtils.isEmpty(oldtime)) {
                String nowYMDHMSTime = TimeUtil.getNowYMDHMSTime();
                SimpleDateFormat CurrentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date startTime = CurrentTime.parse(oldtime);
                    Date endTime = CurrentTime.parse(nowYMDHMSTime);
                    //判断是否大于5分钟
                    Log.v("KYC", "startTime === " + startTime.getTime() +" , endTime === " +endTime.getTime() );
                    long min = ((endTime.getTime() - startTime.getTime()) / 1000) / 60;
                    if (min >= 5 ) {
                        Log.v("KYC", "分钟 === " + min);

                        int tili = (int) (tl + (min / 5));
                        Intent intent=new Intent();
                        intent.putExtra("tili", tili);
                        intent.setAction(ConstactUtil.TimeAction);
                        sendBroadcast(intent);
                    }
                    handler.postDelayed(this,5000);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
    };
}
